import xml.etree.ElementTree as ET
import json

def parse_g_element(g_element):
    """递归解析XML中的<g>元素"""
    node = {
        "name": g_element.get("data-name"),
        "children": [],
        "paths": []
    }
    
    # 提取当前层的路径
    node["paths"].extend(path.get("d") for path in g_element.findall("path"))
    
    # 递归处理子元素
    for child in g_element.findall("g"):
        child_node = parse_g_element(child)      
        if child_node.get("children", []) or len(child_node.get("paths", [])) > 1:
            node["children"].append(child_node)
        else:
            node["paths"].extend(child_node["paths"])
    
    # 清理空字段
    if not node["children"]:
        del node["children"]
    if not node["paths"]:
        del node["paths"]
    
    return node

def save_to_json(data, filename="output.json"):
    """将嵌套字典写入 JSON 文件"""
    with open(filename, "w", encoding="utf-8") as f:
        json.dump(
            data,
            f,
            ensure_ascii=False,  # 支持中文字符
            indent=4,            # 格式化缩进
            sort_keys=False       # 保持原始键顺序
        )
    print(f"数据已保存至 {filename}")

# 示例使用
xml_text = '''

'''


# 解析 XML 并生成嵌套结构
root = ET.fromstring(f"<root>{xml_text}</root>")
parsed_data = [parse_g_element(g) for g in root.findall("g")]

# 写入 JSON 文件
save_to_json(parsed_data, "muscle_structure.json")

